
import sys
import time
import datetime
import os
import os.path as osp
import yaml
from time import strftime

import httplib 
import json
import logging

curDir = sys.path[0]
BatchPath = osp.join(curDir, 'SAIC_Batch_Analyze')
sys.path.append(BatchPath)
import BatchEstimation

startEndPath = osp.join(curDir, 'oss_det_fea','tools')
sys.path.append(startEndPath)
import start_end

logger = logging.getLogger()
logger.setLevel(logging.INFO)
rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
logfile = '/data/hd/logs/' + rq + '.log'
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)

VIDEO_NUMBER_ONE_DAY = 3240# 9h * 60 *6

if __name__ == '__main__':

	try:
		res = {}

		startRunTime = time.strftime("%Y-%m-%d %H:%M:%S") #datetime.datetime.now()

		configPath = osp.join(curDir, 'oss_det_fea', 'tools','config.yaml')
		sysConfig = yaml.load(open(configPath))
		
		cameraidlst = sysConfig['camera_order']
		shoplst = sysConfig['shopId_order']		
		print(shoplst)
		print(cameraidlst)
		logger.info(shoplst)
		logger.info(cameraidlst)
		
		reqHost = sysConfig['returnUrl']['host']
		reqPort = sysConfig['returnUrl']['resultPort']
		exceptionPort = sysConfig['returnUrl']['exceptionPort']

		print("step1")
		print(time.time())
		logger.info("step1")
		
		strftime("%m/%d/%Y %H:%M")
		curDate = time.strftime("%Y%m%d")
		print(curDate)
		logger.info("current date: "+ str(curDate))
		
		os.chdir(curDir + str("/oss_det_fea/tools"))
                
        linearPredict = 1.0
        videoNum = start_end.startEnd('config.yaml')
		logger.info("video number: " + str(videoNum))
        if videoNum < VIDEO_NUMBER_ONE_DAY and videoNum != 0:
            linearPredict = float(VIDEO_NUMBER_ONE_DAY) / videoNum

		print("step2")
		print(time.time())
		logger.info("step2")
		
		os.chdir(curDir + str("/deep_track"))
		cmd2 = "python deep_track_app_new.py --max_cosine_distance 0.2 --min_confidence 0.3 --nn_budget 100 --detection_dir ../example/oss_det_fea/featureOutput/"
		for iterr in range(len(shoplst)):			
			execcmd2 = cmd2 + str(shoplst[iterr]) + "/" + str(curDate) + "/Channel_0" + str(cameraidlst[iterr]) + "/Append "
			execcmd2 = execcmd2 + "--output_file ../example/deep_track/" + str(shoplst[iterr]) + "/" + str(curDate) + "/" + "track_match_Channel_0" + str(cameraidlst[iterr]) + ".csv"
			print execcmd2
			logger.info(execcmd2)
			os.system(execcmd2)
		
		print "step3"
		print(time.time())
		logger.info("step3")
		
		reslst = []			
		os.chdir(curDir + str("/SAIC_Batch_Analyze"))
		cmd3 = "python BatchEstimation.py "
		for iterr in range(len(shoplst)):
			resultData = {}
			resultData["shopId"] = 	shoplst[iterr]
			resultData["cameraId"] = cameraidlst[iterr]

			execcmd3 = "../example/deep_track/" + str(shoplst[iterr]) + "/" + str(curDate)
			print(execcmd3)
			logger.info(execcmd3)
			allBatch,saleServiceNum = BatchEstimation.batchCalculator(execcmd3)
                        
			resultData["receptCount"] = saleServiceNum
			resultData["batchCount"] = int(allBatch * linearPredict)
			resultData["date"] = str(startRunTime)
			reslst.append(resultData)

		res["status"] = 0
		res["resultMessage"] = 'success'
		res["resultData"] = reslst

	except Exception as e:

		res = {}
		res["entityCode"] = shoplst
		res["errorCode"] = 1000
		res["errorDesc"] = str(e)
        res["cameraCode"] = cameraidlst
        res["errorLevel"] = 1000
		res["reportDate"] = str(startRunTime)
		reqPort = exceptionPort

	finally:

		os.chdir('/data/hd/logs/')
		requrl = "http://" + str(reqHost) + ":" + str(reqPort)
		conn = httplib.HTTPConnection(str(reqHost),reqPort)
		headerdata = {"Content-type": "application/json"}		
		#conn.request('POST',requrl,json.dumps(res),headerdata) 
		
		fo = open(str(curDate)+".txt",'w')
        logger.info(str(curDate)+".txt")
        fo.write(str(res))
        fo.close()

		print(res)
		logger.info(str(res))
		print(time.time())		
		print("End Service")
		logger.info("End Service")
		
		sys.exit()
